package cn.xeblog.server.action.timer;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author ZhangLei
 * @date 2024/2/5 15:35
 */
public class TimerUtil {

    /**
     * 开启一个计时器，默认10秒
     *
     * @param timerAction 计时器业务
     */
    public static void startTimer(TimerAction timerAction) {
        startTimer(timerAction, 10);
    }

    /**
     * 开启一个计时器
     *
     * @param timerAction 计时器业务
     * @param duration    持续时间/秒
     */
    public static void startTimer(TimerAction timerAction, int duration) {
        Date overTime = new Date(new Date().getTime() + duration * 1000L);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (new Date().after(overTime)) {
                    timerAction.timingEnds(overTime);
                    timer.cancel();
                } else {
                    timerAction.timingBegins(overTime);
                }
            }
        }, 0, 1000); // 每隔 1 秒执行一次任务
    }
}
